import React, { useEffect, useState } from 'react'
import {Button, Image, Space} from 'antd'
/**
 * 1. axios 配置
 * 2. 拦截器
 * 3. 类型
 * 
 */
import axios from 'axios'
import { Table } from 'antd'
import { ColumnsType } from 'antd/es/table'
const request = axios.create({
    baseURL:'https://api.github.com/',
    timeout:20000
})
request.interceptors.response.use(response=>response.data)

// ts中发送ajax请求，需要定义响应结果的类型，否则，语法检查过不去
interface IUser{
    avatar_url:string,
    html_url:string,
    id:number,
    login:string
}
type IUsers = IUser[]

interface IResponse {
    items:IUsers
}


export default function AxiosTable() {
    // 定义状态数据
    let [users, setUsers] = useState<IUsers>()
    let [total, setTotal] = useState<number>(10)
    let [current,setCurrent] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(3)
    useEffect(() => {
        async function _getUsers(){
            // TS语法检查在先，代码运行在后，所以发送ajax请求需要先定义成功结果值的类型，否则语法检查过不了。
            let {items} = await request.get<any,IResponse>('/search/users',{
                params:{
                    q:'aa'
                }
            })
            // console.log('res: ', res.items[0].)
            console.log('items', items)
            // 设置users状态数据
            setUsers(items)
            // 设置总条数
            setTotal(items.length)

        }
        _getUsers()
    }, [])

    const columns:ColumnsType<IUser> = [
        {
            title:'id',
            dataIndex:'id'
        },
        {
            title:'用户名',
            dataIndex:'login'
        },
        {
            title:'头像',
            dataIndex:'avatar_url',
            render(value:string){
                return <Image src={value} width={100}/>
            }
        },
        {
            title:'操作',
            render(){
                return (
                    <Space>
                        <Button>删除</Button>
                        <Button>编辑</Button>
                    </Space>
                )
            }
        }
    ]
    return (
        <div>
            <h3>TestAxios</h3>
            <Table
                rowKey={'id'}
                columns={columns}
                dataSource={users}
                pagination={{
                    current,
                    pageSize,
                    total,
                    showSizeChanger:true,
                    pageSizeOptions:[5,10,15],
                    onChange:(page:number,pageSize:number)=>{
                        setCurrent(page)
                        setPageSize(pageSize)
                    }
                }}
            />
        </div>
    )
}
